package com.tanhua.server.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.dubbo.server.api.SoundApi;
import com.tanhua.dubbo.server.api.UserLikeApi;
import com.tanhua.dubbo.server.api.UserLocationApi;
import com.tanhua.dubbo.server.pojo.RecommendUser;
import com.tanhua.dubbo.server.pojo.Sound;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.dubbo.server.vo.UserLocationVo;
import com.tanhua.server.enums.SexEnum;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.mapper.*;
import com.tanhua.server.pojo.*;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.*;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.*;

@Service
public class TodayBestService {

    private static final ObjectMapper MAPPER = new ObjectMapper();

    @Reference(version = "1.0.0")
    private UserLocationApi userLocationApi;

    @Reference(version = "1.0.0")
    private UserLikeApi userLikeApi;

    @Reference(version = "1.0.0")
    private SoundApi soundApi;

    @Autowired
    private QuestionnaireResultMapper questionnaireResultMapper;

    @Autowired
    private QuestionUserLockMapper questionUserLockMapper;

    @Autowired
    private QuestionnaireMapper questionnaireMapper;

    @Autowired
    private PicUploadService picUploadService;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private QuestionnaireReportMapper questionnaireReportMapper;

    @Autowired
    private SoulQuestionOptionMapper soulQuestionOptionMapper;

    @Autowired
    private RecommendUserService recommendUserService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private UserInfoService userInfoService;

    /*@Autowired
    private UserService userService;*/

    @Autowired
    private IMService imService;

    @Autowired
    private QuestionService questionService;

    @Autowired
    private SoulQuestionMapper soulQuestionMapper;

    @Value("${tanhua.sso.default.user}")
    private Long defaultUserId;

    @Value("${tanhua.sso.url}")
    private String ssoUrl;

    @Autowired
    private RestTemplate restTemplate;

    @Value("${tanhua.sso.default.recommend.users}")
    private String defaultRecommendUsers;

    //public TodayBest queryTodayBest(String token) {
    public TodayBest queryTodayBest() {
        //查询当前的登录信息
        //User user = this.userService.queryUserByToken(token);
        User user = UserThreadLocal.get();
        if (null == user) {
            return null;
        }

        //查询今日佳人
        TodayBest todayBest = this.recommendUserService.queryTodayBest(user.getId());
        if (null == todayBest) {
            // 默认推荐用户
            todayBest = new TodayBest();
            todayBest.setId(defaultUserId);
            todayBest.setFateValue(95L);
        }

        //补全信息
        UserInfo userInfo = this.userInfoService.queryById(todayBest.getId());
        todayBest.setAge(userInfo.getAge());
        todayBest.setAvatar(userInfo.getLogo());
        todayBest.setGender(userInfo.getSex().toString());
        todayBest.setNickname(userInfo.getNickName());
        todayBest.setTags(StringUtils.split(userInfo.getTags(), ','));

        return todayBest;
    }

    /**
     * 查询推荐用户列表
     *
     * @param queryParam //* @param token
     * @return
     */
    //public PageResult queryRecommendUserList(RecommendUserQueryParam queryParam, String token) {
    public PageResult queryRecommendUserList(RecommendUserQueryParam queryParam) {
        //查询当前的登录信息
        //User user = this.userService.queryUserByToken(token);
        User user = UserThreadLocal.get();
        if (null == user) {
            return null;
        }

        PageResult pageResult = new PageResult();
        PageInfo<RecommendUser> pageInfo = this.recommendUserService.queryRecommendUserList(user.getId(), queryParam.getPage(), queryParam.getPagesize());

        pageResult.setCounts(0); //前端不参与计算，仅需要返回字段
        pageResult.setPage(queryParam.getPage());
        pageResult.setPagesize(queryParam.getPagesize());

        //获取推荐对象列表
        List<RecommendUser> records = pageInfo.getRecords();

        //如果没查询到,需要使用默认推荐列表
        if (CollectionUtils.isEmpty(records)) {
            String[] split = StringUtils.split(defaultRecommendUsers, ',');
            for (String s : split) {
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setUserId(Long.valueOf(s));
                recommendUser.setToUserId(Long.valueOf(user.getId()));
                recommendUser.setScore(RandomUtils.nextDouble(70, 90));
                records.add(recommendUser);
            }
        }

        List<Long> userIds = new ArrayList<>();
        for (RecommendUser record : records) {
            userIds.add(record.getUserId());
        }

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIds);

        //queryParam是筛选条件,方便测试先注释掉
        /*if (StringUtils.isNotEmpty(queryParam.getGender())) { //性别条件
            if (queryParam.getGender().equals("man")) {
                queryWrapper.eq("sex", 1);
            } else {
                queryWrapper.eq("sex", 2);
            }
        }

        if (StringUtils.isNotEmpty(queryParam.getCity())) { //居住城市
            queryWrapper.eq("city", queryParam.getCity());
        }

        if (queryParam.getAge() != null) { //年龄
            queryWrapper.lt("age", queryParam.getAge());
        }*/

        List<UserInfo> userInfos = this.userInfoService.queryUserInfoList(queryWrapper);

        List<TodayBest> todayRecommends = new ArrayList<>();
        for (UserInfo userInfo : userInfos) {
            TodayBest todayRecommend = new TodayBest();
            todayRecommend.setId(userInfo.getUserId());
            todayRecommend.setAge(userInfo.getAge());
            todayRecommend.setAvatar(userInfo.getLogo());
            todayRecommend.setGender(userInfo.getSex().name().toLowerCase());
            todayRecommend.setNickname(userInfo.getNickName());
            todayRecommend.setTags(StringUtils.split(userInfo.getTags(), ','));

            //设置缘分值
            for (RecommendUser record : records) {
                if (userInfo.getUserId().longValue() == record.getUserId().longValue()) {
                    double score = Math.floor(record.getScore());
                    todayRecommend.setFateValue(Double.valueOf(score).longValue());
                    break;
                }
            }

            todayRecommends.add(todayRecommend);
        }

        //排序集合，按照score倒序排序
        Collections.sort(todayRecommends, (o1, o2) -> new Long(o2.getFateValue() - o1.getFateValue()).intValue());

        /*Collections.sort(todayBests, new Comparator<TodayBest>() {
            @Override
            public int compare(TodayBest o1, TodayBest o2) {
                return new Long(o2.getFateValue() - o1.getFateValue()).intValue();
            }
        });*/
        pageResult.setItems(todayRecommends);

        return pageResult;
    }

    /**
     * 查询今日佳人详情
     *
     * @param userId
     * @return
     */
    public TodayBest queryTodayBest(Long userId) {

        User user = UserThreadLocal.get();

        TodayBest todayBest = new TodayBest();
        //补全信息
        UserInfo userInfo = this.userInfoService.queryById(userId);
        todayBest.setId(userId);
        todayBest.setAge(userInfo.getAge());
        todayBest.setAvatar(userInfo.getLogo());
        todayBest.setGender(userInfo.getSex().name().toLowerCase());
        todayBest.setNickname(userInfo.getNickName());
        todayBest.setTags(StringUtils.split(userInfo.getTags(), ','));

        double score = this.recommendUserService.queryScore(userId, user.getId());
        if (score == 0) {
            score = 98; //默认分值
        }

        todayBest.setFateValue(Double.valueOf(score).longValue());

        return todayBest;
    }

    /**
     * 查询陌生人问题
     *
     * @param userId
     * @return
     */
    public String queryQuestion(Long userId) {
        Question question = this.questionService.queryQuestion(userId);
        if (null != question) {
            return question.getTxt();
        }
        return "";
    }

    /**
     * 回复陌生人问题，发送消息给对方
     *
     * @param userId
     * @param reply
     * @return
     */
    public Boolean replyQuestion(Long userId, String reply) {
        User user = UserThreadLocal.get();
        UserInfo userInfo = this.userInfoService.queryById(user.getId());

        //构建消息内容
        Map<String, Object> msg = new HashMap<>();
        msg.put("userId", user.getId().toString());
        msg.put("nickname", this.queryQuestion(userId));
        msg.put("strangerQuestion", userInfo.getNickName());

        //msg.put("nickname", userInfo.getNickName());
        //msg.put("strangerQuestion", this.queryQuestion(userId));

        msg.put("reply", reply);

        try {
            String msgStr = MAPPER.writeValueAsString(msg);

            String targetUrl = this.ssoUrl + "/user/huanxin/messages";

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

            MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
            params.add("target", userId.toString());
            params.add("msg", msgStr);

            HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(params, headers);

            ResponseEntity<Void> responseEntity = this.restTemplate.postForEntity(targetUrl, httpEntity, Void.class);

            return responseEntity.getStatusCodeValue() == 200;
        } catch (Exception e) {
            e.printStackTrace();
        }


        return false;
    }

    /**
     * 搜附近
     *
     * @param gender
     * @param distance
     * @return
     */
    public List<NearUserVo> queryNearUser(String gender, String distance) {
        User user = UserThreadLocal.get();
        // 查询当前用户的位置信息
        UserLocationVo userLocationVo = this.userLocationApi.queryByUserId(user.getId());
        Double longitude = userLocationVo.getLongitude();
        Double latitude = userLocationVo.getLatitude();

        // 根据当前用户的位置信息查询附近的好友
        List<UserLocationVo> userLocationList = this.userLocationApi
                .queryUserFromLocation(longitude, latitude, Integer.valueOf(distance));

        if (CollectionUtils.isEmpty(userLocationList)) {
            return Collections.emptyList();
        }

        List<Long> userIds = new ArrayList<>();
        for (UserLocationVo locationVo : userLocationList) {
            userIds.add(locationVo.getUserId());
        }
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIds);
        if (StringUtils.equalsIgnoreCase(gender, "man")) {
            queryWrapper.in("sex", SexEnum.MAN);
        } else if (StringUtils.equalsIgnoreCase(gender, "woman")) {
            queryWrapper.in("sex", SexEnum.WOMAN);
        }

        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(queryWrapper);

        List<NearUserVo> nearUserVoList = new ArrayList<>();

        for (UserLocationVo locationVo : userLocationList) {

            if (locationVo.getUserId().longValue() == user.getId().longValue()) {
                // 排除自己
                continue;
            }

            for (UserInfo userInfo : userInfoList) {
                if (locationVo.getUserId().longValue() == userInfo.getUserId().longValue()) {
                    NearUserVo nearUserVo = new NearUserVo();

                    nearUserVo.setUserId(userInfo.getUserId());
                    nearUserVo.setAvatar(userInfo.getLogo());
                    nearUserVo.setNickname(userInfo.getNickName());

                    nearUserVoList.add(nearUserVo);
                    break;
                }
            }
        }

        return nearUserVoList;
    }

    /**
     * 探花
     *
     * @return
     */
    public List<TodayBest> queryCardsList() {
        User user = UserThreadLocal.get();
        int count = 50;

        PageInfo<RecommendUser> pageInfo = this.recommendUserService.queryRecommendUserList(user.getId(), 1, count);
        if (CollectionUtils.isEmpty(pageInfo.getRecords())) {
            //默认推荐列表
            String[] ss = StringUtils.split(defaultRecommendUsers, ',');
            for (String s : ss) {
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setUserId(Long.valueOf(s));
                recommendUser.setToUserId(user.getId());
                pageInfo.getRecords().add(recommendUser);
            }
        }

        List<RecommendUser> records = pageInfo.getRecords();
        int showCount = Math.min(10, records.size());

        List<RecommendUser> newRecords = new ArrayList<>();
        for (int i = 0; i < showCount; i++) {
            //随机选出推荐的好友
            createRecommendUser(newRecords, records);
        }

        List<Long> userIds = new ArrayList<>();
        for (RecommendUser record : newRecords) {
            userIds.add(record.getUserId());
        }

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIds);

        List<UserInfo> userInfos = this.userInfoService.queryUserInfoList(queryWrapper);
        List<TodayBest> todayBests = new ArrayList<>();
        for (UserInfo userInfo : userInfos) {
            TodayBest todayBest = new TodayBest();
            todayBest.setId(userInfo.getUserId());
            todayBest.setAge(userInfo.getAge());
            todayBest.setAvatar(userInfo.getLogo());
            todayBest.setGender(userInfo.getSex().name().toLowerCase());
            todayBest.setNickname(userInfo.getNickName());
            todayBest.setTags(StringUtils.split(userInfo.getTags(), ','));
            //todayBest.setFateValue(0L);

            todayBests.add(todayBest);
        }

        return todayBests;
    }

    /**
     * 递归随机生成推荐好友,保证不重复
     */
    private void createRecommendUser(List<RecommendUser> newRecommendUserList, List<RecommendUser> records) {
        RecommendUser recommendUser = records.get(RandomUtils.nextInt(0, records.size() - 1));
        if (!newRecommendUserList.contains(recommendUser)) {
            newRecommendUserList.add(recommendUser);
        } else {
            //开始递归
            createRecommendUser(newRecommendUserList, records);
        }
    }

    /**
     * 喜欢
     *
     * @param likeUserId
     * @return
     */
    public Boolean likeUser(Long likeUserId) {
        User user = UserThreadLocal.get();
        String id = this.userLikeApi.saveUserLike(user.getId(), likeUserId);
        if (StringUtils.isEmpty(id)) {
            return false;
        }

        if (this.userLikeApi.isMutualLike(user.getId(), likeUserId)) {
            //相互喜欢成为好友
            this.imService.contactUser(likeUserId);
        }
        return true;
    }

    /**
     * 不喜欢
     *
     * @param likeUserId
     * @return
     */
    public Boolean disLikeUser(Long likeUserId) {
        User user = UserThreadLocal.get();
        //删除mongoDB和环信的好友关系 TODO
        return this.userLikeApi.deleteUserLike(user.getId(), likeUserId);
    }

    /**
     * 发送传音
     *
     * @param soundFile
     * @return
     */
    public boolean saveSound(MultipartFile soundFile) {
        User user = UserThreadLocal.get();

        //创建redis语音键(传音只能10次)
        //在redis里设置一个唯一的缓存键，根据当天的时间设置，并且根据下面的清除缓存设置清除
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dateTime = simpleDateFormat.format(date);
        String key = user.getId() + "_" + dateTime + "_SEND_SOUND";

        //判断
        String keyValue = redisTemplate.opsForValue().get(key);
        if (null == keyValue) {
            redisTemplate.opsForValue().set(key, "9", Duration.ofDays(1));
        } else if (keyValue.equals("0")) {
            return false;
        } else {
            redisTemplate.opsForValue().decrement(key);
            //redisTemplate.boundValueOps(key).increment(-1L);
        }

        UserInfo userInfo = this.userInfoService.queryById(user.getId());
        Sound sound = new Sound();
        sound.setUserId(user.getId());
        /*sound.setAvatar(userInfo.getLogo());
        sound.setAge(userInfo.getAge());
        sound.setNickname(userInfo.getNickName());*/
        sound.setGender(userInfo.getSex().name());
        try {
            //把声音文件上传到oss上，把sound文件保存到MongoDB上，两种同时成功，返回true给controller
            //上传语音
            PicUploadResult upload = picUploadService.upload(soundFile);
            sound.setSoundUrl(upload.getName());
            this.soundApi.saveSound(sound);
            return true;
        } catch (Exception e) {
            throw new BusinessException("上传失败");
        }
    }

    /**
     * 接收传音
     *
     * @return
     */
    public SoundVo querySound() {
        User user = UserThreadLocal.get();
        //判断他的接收次数
        //创建redis键(接收传音每天只能10次)
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dateTime = simpleDateFormat.format(date);
        //记当天的接收次数
        String key = user.getId() + "_" + dateTime + "_GET_SOUND";

        //判断
        String keyValue = redisTemplate.opsForValue().get(key);
        if (null == keyValue) {
            redisTemplate.opsForValue().set(key, "9", Duration.ofDays(1));
        } else if (keyValue.equals("0")) {
            return null;
        } else {
            redisTemplate.opsForValue().decrement(key);

        }
//
        //获取到所有人声音文件的集合
        List<Sound> sounds = soundApi.querySounds();

        //通过createSoundUserId方法，传入sounds和当前用户的对象，随机获取非当前用户的传音
        Sound sound = createSoundUserId(sounds, userInfoService.queryById(user.getId()));
        UserInfo userInfo = userInfoService.queryById(sound.getUserId());

        //返回响应
        SoundVo soundVo = new SoundVo();
        soundVo.setUserId(sound.getUserId());
        soundVo.setAvatar(userInfo.getLogo());
        soundVo.setNickname(userInfo.getNickName());
        soundVo.setGender(SexEnum.getSexByValue(userInfo.getSex().getValue()));
        soundVo.setAge(userInfo.getAge());
        soundVo.setSoundUrl(sound.getSoundUrl());
        int count = Integer.parseInt(redisTemplate.opsForValue().get(key));
        soundVo.setRemainingTimes(count);
        return soundVo;

    }

    /**
     * 随机获取非当前用户的传音
     * 排除自己的和已获取过的
     *
     * @param sounds
     * @param userInfo
     * @return
     */
    private Sound createSoundUserId(List<Sound> sounds, UserInfo userInfo) {
        //获得任意一个sound声音对象
        Sound sound = sounds.get(RandomUtils.nextInt(0, sounds.size() - 1));
        /*QueryWrapper<UserInfo>queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_id",sound.getUserId());
        UserInfo soundUser = this.userInfoMapper.selectOne(queryWrapper);*/
        //UserInfo soundUser = userInfoMapper.selectById(sound.getUserId());
        //判断,非自己,异性,不重复
        if (sound.getUserId() == userInfo.getUserId()
                || sound.getGender().equals(userInfo.getSex().name())) {
            if(redisTemplate.opsForHash().hasKey("sound", sound.getSoundUrl())==null){
                redisTemplate.opsForHash().put("sound", sound.getSoundUrl(), "0");
                return sound;
            }else if(redisTemplate.opsForHash().hasKey("sound", sound.getSoundUrl())){
                createSoundUserId(sounds, userInfo);
            }
        }
        redisTemplate.opsForHash().put("sound", sound.getSoundUrl(), "0");
        return sound;
    }

    /**
     * 问卷列表
     * @return
     */
    public List<QuestionnaireVo> SQuestionnaireLike() {
        //拿到用户id
        User user = UserThreadLocal.get();
        //要返回的vo对象
        List<QuestionnaireVo> questionnaireVoList = new ArrayList<>();
        //通过user_Id找到QuestionUserLock表中的user_id拿到问卷id和锁状态存到问卷vo里面
        QueryWrapper<QuestionUserLock> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("user_id", user.getId());
        List<QuestionUserLock> questionUserLock = this.questionUserLockMapper.selectList(queryWrapper1);
        for (QuestionUserLock questionUserLocks : questionUserLock) {
            QuestionnaireVo questionnaireVo = new QuestionnaireVo();
            questionnaireVo.setId(questionUserLocks.getQuestionnaireId());
            questionnaireVo.setIsLock(questionUserLocks.getIsLock());
            questionnaireVoList.add(questionnaireVo);
        }

        //拿出问卷Id的集合
        List<Long> questionnaireId = new ArrayList();
        for (QuestionUserLock UserId : questionUserLock) {
            questionnaireId.add(UserId.getQuestionnaireId());
            System.out.println(UserId.getQuestionnaireId());
        }

        //通过拿到的问卷id找到问题表中的数据存在返回问卷vo中
        QueryWrapper<Questionnaire> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.in("id", questionnaireId);
        List<Questionnaire> soulQuestionnaire = this.questionnaireMapper.selectList(queryWrapper2);
        for (Questionnaire questionnaire : soulQuestionnaire) {
            for (QuestionnaireVo questionnaireVo : questionnaireVoList) {
                //把返回vo中的id与从问题表中拿到的id进行对比,确定存放的是同一个vo返回对象
                if (questionnaire.getId().toString().equals(questionnaireVo.getId().toString())) {
                    questionnaireVo.setLevel(questionnaire.getLevel());
                    questionnaireVo.setName(questionnaire.getName());
                    questionnaireVo.setCover(questionnaire.getCover());
                    questionnaireVo.setStar(questionnaire.getStar());
                }
            }
        }

        //把问题vo填充到问卷vo中
        for (QuestionnaireVo questionnaireVo : questionnaireVoList) {
            //拿到试题数据
            QueryWrapper<SoulQuestion> queryWrapper3 = new QueryWrapper<>();
            queryWrapper3.in("questionnaire_id", questionnaireId);
            //List<SoulQuestionVo> questions;字段中还缺少SoulQuestionVo集合
            //从数据库中拿到SoulQuestionVo信息
            List<SoulQuestion> soulQuestions = this.soulQuestionMapper.selectList(queryWrapper3);
            List<SoulQuestionVo> soulQuestionVos = new ArrayList<>();
            //填充SoulQuestionVo的数据
            for (SoulQuestion soulQuestion : soulQuestions) {
                SoulQuestionVo soulQuestionVo = new SoulQuestionVo();
                soulQuestionVo.setId(String.valueOf(soulQuestion.getId()));
                soulQuestionVo.setQuestion(soulQuestion.getStem());
                soulQuestionVos.add(soulQuestionVo);
                //SoulQuestionVo中还有一个List<SoulQuestionOptionVo> options-----选项集合没有填充
                QueryWrapper<SoulQuestionOption> queryWrapper4 = new QueryWrapper<>();
                queryWrapper4.in("question_id", soulQuestion.getId());
                List<SoulQuestionOption> soulQuestionList = this.soulQuestionOptionMapper.selectList(queryWrapper4);
                List<SoulQuestionOptionVo> soulQuestionOptionVo = new ArrayList<>();
                //填充soulQuestionOptionVo1数据
                for (SoulQuestionOption option : soulQuestionList) {
                    SoulQuestionOptionVo soulQuestionOptionVo1 = new SoulQuestionOptionVo();
                    soulQuestionOptionVo1.setId(String.valueOf(option.getId()));
                    soulQuestionOptionVo1.setOption(option.getContent());
                    soulQuestionOptionVo.add(soulQuestionOptionVo1);
                }
                //把选项vo集合填充到问题对象中
                soulQuestionVo.setOptions(soulQuestionOptionVo);
            }
            //把问题对象填充到返回问卷vo对象
            questionnaireVo.setQuestions(soulQuestionVos);

        }
        return questionnaireVoList;
    }

    /**
     * 测灵魂题目提交
     *
     * @param answersList
     */
    public void testSoul(List<Answers> answersList) {
        Integer score = 0;
        Long questionId = 0L;

        //计算分数
        for (Answers answers : answersList) {
            questionId = answers.getQuestionId();
            Long optionId = answers.getOptionId();
            QueryWrapper queryWrapper = new QueryWrapper();
            //queryWrapper.eq("question_id", questionId);
            queryWrapper.eq("id", optionId);
            SoulQuestionOption soulQuestionOption = soulQuestionOptionMapper.selectOne(queryWrapper);
            score += Integer.parseInt(soulQuestionOption.getScore());
        }

        System.out.println(score);

        //通过题目id查到对应的问卷id
        SoulQuestion soulQuestion = soulQuestionMapper.selectById(questionId);
        Long questionnaireId = soulQuestion.getQuestionnaireId();

        //默认初级开启
        QueryWrapper<QuestionUserLock> queryWrapper = new QueryWrapper();
        if (questionnaireId<=2){
            queryWrapper.eq("questionnaire_id", questionnaireId+1);
            QuestionUserLock questionUserLock = questionUserLockMapper.selectOne(queryWrapper);
            if(questionUserLock.getIsLock().equals(1)){
                questionUserLock.setIsLock(0);
                questionUserLockMapper.update(questionUserLock,queryWrapper);
            }
        }
        //根据问卷id,查看结果表，看总分在哪个区间，判断你的性格，并把数据都添加到报告表里
        QueryWrapper<QuestionnaireResult> query3 = new QueryWrapper<>();
        query3.eq("questionnaire_id", questionnaireId);
        List<QuestionnaireResult> questionnaireResults = questionnaireResultMapper.selectList(query3);

        QuestionnaireReport questionnaireReport = new QuestionnaireReport();
        questionnaireReport.setUserId(UserThreadLocal.get().getId());
        questionnaireReport.setQuestionnaireId(questionnaireId);
        for (QuestionnaireResult questionnaireResult : questionnaireResults) {
            String[] split = questionnaireResult.getScope().split(",");
            if (score >= Integer.valueOf(split[0]) && score <= Integer.valueOf(split[1])) {
                questionnaireReport.setResultId(questionnaireResult.getId());
                break;
            }
        }
        questionnaireReportMapper.insert(questionnaireReport);
    }

    /**
     * 灵魂测试结果
     * @param id
     * @return
     */
    public TestResultVo testResult(Long id) {
        TestResultVo testResultVo = new TestResultVo();
        List<Dimensions> dimensionList = new ArrayList<>();
        //通过id获取报告里面的数据
        QuestionnaireReport questionnaireReport = questionnaireReportMapper.selectById(id);
        Long resultId = questionnaireReport.getResultId();
        //通过报告表里面的resultId查询数据，写维度集合里
        QuestionnaireResult questionnaireResult = questionnaireResultMapper.selectById(resultId);
        dimensionList.add(new Dimensions("extroversion",questionnaireResult.getExtroversion()));
        dimensionList.add(new Dimensions("judgement",questionnaireResult.getJudgement()));
        dimensionList.add(new Dimensions("abstraction",questionnaireResult.getAbstraction()));
        dimensionList.add(new Dimensions("rationality",questionnaireResult.getRationality()));

        //保存到testResultVo里面
        testResultVo.setConclusion(questionnaireResult.getContent());
        testResultVo.setCover(questionnaireResult.getCover());
        testResultVo.setDimensions(dimensionList);

        //通过resultId查询报告表，获取所有的用户，存到集合里
        QueryWrapper<QuestionnaireReport> queryWrapper = new QueryWrapper();
        queryWrapper.eq("result_id",resultId);
        List<QuestionnaireReport> questionnaireReports = questionnaireReportMapper.selectList(queryWrapper);
        List<Long> userIds = new ArrayList<>();
        for (QuestionnaireReport report : questionnaireReports) {
            userIds.add(report.getUserId());
        }


        //查询所有用户的完整信息
        QueryWrapper<UserInfo> queryWrapper1 = new QueryWrapper();
        queryWrapper1.in("user_id",userIds);
        List<UserInfo> userInfos = userInfoMapper.selectList(queryWrapper1);

        ArrayList<SimilarYou> similarYouList = new ArrayList<>();
        //如果是当前用户就跳过，否则添加到相似的人集合里
        for (UserInfo userInfo : userInfos) {
            if(UserThreadLocal.get().getId().equals(userInfo.getUserId())){
                continue;
            }
            similarYouList.add(new SimilarYou(userInfo.getUserId(),userInfo.getLogo()));
        }

        testResultVo.setSimilarYou(similarYouList);
        return testResultVo;
    }

}
